<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Intervention\Image\Facades\Image;

class LinkController extends Controller
{
    public function index()
    {
        //查询数据库
        $result = DB::table('link')->get();
        //返回数据
        return view('admin/link', ['result' => $result]);
    }

    public function add()
    {
        //跳转页面
        return view('admin/linkadd');

    }

    //添加方法实现
    public function insert(Request $request)
    {
        //接收数据
        $name = $request->name;
        $url = $request->url;
        $img = $request->img;
        //存入数组
        $data = array(
            'name' => $name,
            'url' => $url,
            'img' => $img
        );
        //存入数据库
        $result = DB::table('link')->insert($data);
        if ($result) {
            return redirect('/prompt')->with(['message' => '添加链接成功！', 'url' => '/adm/link', 'jumpTime' => 3, 'status' => true]);
        } else {
            return redirect('/prompt')->with(['message' => '添加链接失败！', 'url' => '/adm/link/add', 'jumpTime' => 3, 'status' => true]);
        }
    }

    //编辑链接
    public function upd($id)
    {
        //接收id
        $id = $id;
        //查询数据
        $result = DB::table('link')->where('id', $id)->get();
        if ($result) {
            //跳转
            return view('/admin/linkupdate', ['result' => $result]);
        }
    }

    //编辑修改方法
    public function update(Request $request)
    {
        //接收数据
        $id = $request->id;
        $name = $request->name;
        $url = $request->url;
        $img = $request->img;

        //存入数组中
        $data = array(
            'name' => $name,
            'url' => $url,
            'img' => $img
        );

        //修改
        $result = DB::table('link')
            ->where('id', $id)
            ->update([
                'name' => $name,
                'url' => $url,
                'img' => $img
            ]);

        if ($result) {
            return redirect('/prompt')->with(['message' => '编辑链接成功！', 'url' => '/adm/link', 'jumpTime' => 3, 'status' => true]);
        } else{
            return redirect('/prompt')->with(['message' => '编辑链接失败！', 'url' => '/adm/link/upd/'.$id, 'jumpTime' => 3, 'status' => true]);
        }

    }

    //删除
    public function del($id)
    {
        //接收数据
        $id = $id;

        $result = DB::delete('delete from `link` where id=' . $id);

        if ($result) {
            echo 1;
        } else {
            echo 2;
        }
    }


}
